package com.example.demo2.demo07;

import com.example.demo2.rabbitmq.RabbitMQConnection;
import com.rabbitmq.client.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Description: 消费者 - 延时队列 - 手动应答(autoAck= false)
 * @Author: mingtian
 * @CreateDate: 2021/1/18 09:42
 * @Version: 1.0
 */
public class Consumer {

    /**
     * 打印日志
     */
    private static Logger logger = LoggerFactory.getLogger(Producer.class);

    /**
     * 死信队列名称
     */
    private static final String DLX_QUEUE_NAME = "dlx_queue";

    /**
     * 死信交换机名称
     */
    private static final String DLX_EXCHANGE_NAME = "dlx_exchange";

    /**
     * 死信交换机路由key
     */
    private static final String DLX_EXCHANGE_ROUTING_KEY = "dlx_routingKey";

    public static void main(String[] args) throws IOException, TimeoutException {
        logger.info("消费者启动......");
        // 1.创建连接
        Connection connection = RabbitMQConnection.getConnection();
        // 2.设置通道
        Channel channel = connection.createChannel();
        // 指定我们消费者每次批量获取消息的数量
        channel.basicQos(1);
        // 死信队列、交换机、路由键创建以及绑定
        // 声明交换机
        channel.exchangeDeclare(DLX_EXCHANGE_NAME, "direct", true);
        // 声明队列
        channel.queueDeclare(DLX_QUEUE_NAME, true, false, false, null);
        // 队列与交换机绑定
        channel.queueBind(DLX_QUEUE_NAME, DLX_EXCHANGE_NAME, DLX_EXCHANGE_ROUTING_KEY);
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, "UTF-8");
                logger.info("消费者获取消息,msg:{}", msg);
                try {
                    // 消费者完成之后，通知 MQ 服务器端 删除该消息 手动应答模式
                    channel.basicAck(envelope.getDeliveryTag(), false);
                } catch (Exception e) {
                }
            }
        };
        // 3.监听队列  autoAck true:自动应答  false:手动应答
        channel.basicConsume(DLX_QUEUE_NAME, false, defaultConsumer);
    }
}